package lab3_1;

import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;

/**
 * <p>Title: Main program for Lab #3</p>
 * <p>Description: CSIS 343 Lab on 
 *      Basic file I/O
 *      Java Collections
 *      Generics
 *      Exceptions
 *      Assertions
 * </p>
 * 
 * @author tony
 * @date  10.01.2011
 * @email anthony.varghese@uwrf.edu
 * @version 3
 *
 */
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		 * Name of file that will be read in
		 */
		final String INPUT_FILE = "src/lab3_1/Presidents";

		ArrayList<String> list = new ArrayList<String>();

		/*
		 * Open a file and read each line of the file into a list
		 */
		try {
			Scanner input = new Scanner(new FileReader(INPUT_FILE));

			while (input.hasNext()) {
				String line = input.nextLine();
				list.add(line);
			}

			input.close();

		} catch (FileNotFoundException f) {
			System.err.println("Could not open the file: " + INPUT_FILE);
		}

		assert (!list.isEmpty());

		/*
		 * Print the contents of the file that was just read in.
		 */
		for (int i=0; i<list.size(); i++){
			System.out.println( list.get(i) );
		}

		while (true) {
			/*
			 * Get user's search term -- this is what the user wants to search
			 * for in the file.
			 */
			String key = javax.swing.JOptionPane
					.showInputDialog("Enter a search term:");
			System.out.println("Searching for " + key + "...");

			/*
			 * If the user clicks on the "Cancel" button, key will be null.
			 */

			/*
			 * Check if the user clicked on the "OK" button without entering any
			 * text for the key
			 */

			/*
			 * Search for key using a simple linear search
			 */
			boolean found = false;
			for (int i=0; i<list.size(); i++) {
				String x = (String) list.get( i );

				if (x.indexOf(key) >= 0) {
					found = true;

					if ( x.charAt(0) == 'R' )
						System.out.println( "Republican: " + x.substring(2, x.length()) );
					if ( x.charAt(0) == 'D' )
						System.out.println( "Democrat: " + x.substring(2, x.length()) );
				}
			} // end for
			if (!found) {
				System.out.println("  Search term was not found in the list");
			} else {
				System.out.println("... done!");
			}
		}

	}
}
